﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using FastReport;
using FastReport.Preview;

using WCFMINERP.COM;
using WCFMINERP.InnerFactoryContracts.DataContracts;
using System.ServiceModel;
using WCFMINERP.InnerFactoryContracts.InterFaces;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using WCFMINERP.DisjoinProForOutShop.Iview;

namespace WCFMINERP.PrintShopBill.Presenter
{

    public  class MainPresenter
    {
        Report report = new Report();
        Report report1 = new Report();
        Report reportOut = new Report();

        ChannelFactory<IInnerFactory> _proxy;
        IInnerFactory _innerFactory;
        private IMainView _iveiw;

        public List<OrderInfo_Info> orderInfoList = new List<OrderInfo_Info>();
        public MainPresenter(IMainView iveiw)
        {
            _iveiw = iveiw;
            _proxy = new ChannelFactory<IInnerFactory>("IInnerFactory");
            _innerFactory = _proxy.CreateChannel();
            report.Load(Application.StartupPath + "\\PrintShopBill.frx");
            report1.Load(Application.StartupPath + "\\Report\\PrintShopBill.frx");
        }

        /// <summary>
        /// 扫描条码，xz 加
        /// </summary>
        /// <param name="barcode"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public int ReceiveBarcode2(string barcode, out string errorMsg)
        {
            int ret = 0;
            errorMsg = "";

            OrderInfo_Info orderInfo = new OrderInfo_Info();
            ret = _innerFactory.ReceiveBarCode(barcode, InnerFactoryParameter.UserInfo.UserId, InnerFactoryParameter.TechId, out errorMsg, out orderInfo);

            if (ret == 0 && orderInfo.OrderProductId != 0)//接收完成并且产品不为空
            {
                if (orderInfoList.Count > 0)//已扫描列表中存在产品
                {
                    if (orderInfo.ShopName == orderInfoList.First().ShopName)//已扫描列表中的产品和当前扫描产品是同一家影楼
                    {
                        orderInfoList.Add(orderInfo);
                        LinkOrderInfoList();
                    }
                    else
                    {
                        errorMsg = "该产品和已经扫描的产品不是同一家影楼！";
                        ret = 20;
                    }
                }
                else
                {
                    orderInfoList.Add(orderInfo);
                    LinkOrderInfoList();
                }
            }
            return ret;
        }

        public int ReceiveBarcode(string barcode,out string errorMsg)
        {
            int ret =0;
            errorMsg = "";
            if (!orderInfoList.Exists(o => o.OrderProductCode == barcode))//如果该产品还未扫描（OrderInfolist中的产品不存在该条码）
            {

                OrderInfo_Info orderInfo = new OrderInfo_Info();
                ret = _innerFactory.ReceiveBarCode(barcode, InnerFactoryParameter.UserInfo.UserId, InnerFactoryParameter.TechId, out errorMsg, out orderInfo);
                
                if (ret == 0 && orderInfo.OrderProductId != 0)//接收完成并且产品不为空
                {
                    if (orderInfoList.Count > 0)//已扫描列表中存在产品
                    {
                        if (orderInfo.ShopName == orderInfoList.First().ShopName)//已扫描列表中的产品和当前扫描产品是同一家影楼
                        {
                            orderInfoList.Add(orderInfo);
                            LinkOrderInfoList();
                        }
                        else
                        {
                            errorMsg = "该产品和已经扫描的产品不是同一家影楼！";
                            ret = 20;
                        }
                    }
                    else
                    {
                        orderInfoList.Add(orderInfo);
                        LinkOrderInfoList();
                    }
                }
            }
           return ret;
        }

        /// <summary>
        /// 绑定待打印产品列表
        /// </summary>
        private void LinkOrderInfoList()
        {
            _iveiw.LinkOrderInfo(orderInfoList);
        }

        /// <summary>
        /// 打印账单
        /// </summary>
        /// <param name="curTechId"></param>
        /// <param name="operUid"></param>
        /// <param name="SelectOrderInfo"></param>
        /// <param name="hasForcibePrint"></param>
        /// <param name="inPay"></param>
        /// <returns></returns>
        public void PrintShopBill(int curTechId, int operUid, List<OrderInfo_Info> SelectOrderInfo, bool hasForcibePrint, int inPay,out string mess)
        {
            mess = "";
            try
            {
                SHOP_Bill_Info sbInfo= _innerFactory.PrintShopBill(curTechId, operUid, SelectOrderInfo, hasForcibePrint, inPay);
                orderInfoList.Clear();
                LinkOrderInfoList();
                if (sbInfo != null)
                {
                    PrintBill(sbInfo);
                }
            }
            catch (Exception ex)
            {
                mess = ex.Message;
                WriteLogForCheck.WriteLogFile("打印帐单时出错:" + ex.Message);
            }
        }


        /// <summary>
        /// 打印帐单
        /// </summary>
        /// <param name="sbinfo"></param>
        private void PrintBill(SHOP_Bill_Info sbinfo)
        {
            try
            {
                double Para_TotalNum = 0;//照片总张数
                double Para_TotalAreas = 0;//照片总面积
                double Para_TotalCount = 0;//本期金额
                double Para_Sum = 0;//产品总数
                double Para_TotalPrintCount = 0;//输出金额
                double Para_TotalProductCount = 0;//产品金额

                #region//富士打印
                if (sbinfo.IsAssignByCustom)
                {

                }
                #endregion
                #region 组织打印数据

                bool IsNeedPrintMoney = sbinfo.Shop.IsNeedPrintUPrice;
                DataTable tableTitle = CreateShopBillTitle();
                DataRow titleRow = tableTitle.NewRow();
                titleRow["ShopName"] = sbinfo.Shop.shopName;
                titleRow["Tel1"] = sbinfo.Shop.Tel1;
                titleRow["Tel2"] = sbinfo.Shop.Tel2;
                titleRow["ShopId"] = sbinfo.Shop.ShopId;
                titleRow["shopKeeper"] = sbinfo.Shop.shopKeeper;
                titleRow["QQ"] = sbinfo.Shop.QQ;
                titleRow["BillId"] = sbinfo.BillId;
                titleRow["BillOrderCode"] = sbinfo.BillOrderCode;
                titleRow["CreateTime"] = sbinfo.CreateTime;
                titleRow["Adress"] = sbinfo.Shop.address;
                titleRow["CheckOutType"] = sbinfo.CheckType;
                titleRow["Remark"] = sbinfo.Shop.Remark;
                //if (IsNeedPrintMoney)
                //{
                //    titleRow["Balance"] = sbinfo.ShopBalance;
                //    titleRow["BillCount"] = sbinfo.BillCount;
                //}
                //else
                //{
                //    titleRow["Balance"] = 0;
                //    titleRow["BillCount"] = 0;
                //}
                titleRow["Balance"] = sbinfo.ShopBalance;
                titleRow["BillCount"] = sbinfo.BillCount;

                titleRow["Salesman"] = sbinfo.Shop.Salesman;
                titleRow["CreditLevel"] = sbinfo.CreditLevel == null ? 0 : sbinfo.CreditLevel;
                tableTitle.Rows.Add(titleRow);

                tableTitle.TableName = "tableTitle";


                DataTable tableDetail = CreateShopBillDetail();
                DataTable tableSubDetail = CreateShopBillSubDetail();
                List<Bill_Detail_Info> detailList = sbinfo.List_Detail.ToList();

                foreach (Bill_Detail_Info billDetail in detailList)
                {
                    DataRow row = tableDetail.NewRow();
                    row["BillDetailId"] = billDetail.BillDetailId;
                    row["OrderInfoCode"] = billDetail.OrderInfoCode;
                    row["OrderProductName"] = billDetail.OrderProductName;
                    row["CtmName"] = billDetail.CtmName;
                    row["Remark"] = billDetail.Remark;
                    row["OrderBagName"] = billDetail.OrderBagName;

                    tableDetail.Rows.Add(row);
                    List<Bill_Detail_Detail_Info> subDetail = billDetail.ListDetail_Detail.ToList();
                    foreach (Bill_Detail_Detail_Info detail in subDetail)
                    {
                        DataRow rowSub = tableSubDetail.NewRow();
                        rowSub["DetailName"] = detail.DetailName;
                        rowSub["BillDetailId"] = billDetail.BillDetailId;
                        rowSub["Spec"] = detail.Spec;
                        rowSub["Num"] = detail.Num;
                        rowSub["UnitPrice"] = detail.UnitPrice;
                        rowSub["DetailRemark"] = detail.DetailRemark;
                        if (IsNeedPrintMoney)
                        {
                            rowSub["Count"] = detail.Count;
                        }
                        else
                        {
                            rowSub["Count"] = 0;
                        }

                        rowSub["Area"] = detail.Area;
                        rowSub["Type"] = detail.Type;
                        tableSubDetail.Rows.Add(rowSub);

                        if (detail.Type == 1)//是输出类型
                        {
                            Para_TotalNum += detail.Num;
                            Para_TotalAreas += detail.Area;
                            Para_TotalPrintCount += detail.Count;
                        }
                        else if (detail.Type == 0)
                        {
                            Para_TotalProductCount += detail.Count;
                        }
                        Para_TotalCount += detail.Count;
                    }
                    Para_Sum++;
                }

                tableDetail.TableName = "tableDetail";
                tableSubDetail.TableName = "tableSubDetail";

                #region
               

                #endregion
                #endregion

                #region //获取发货信息
                DataTable tableBottom = CreateFahuoTable();
                DataRow bottomeRow = tableBottom.NewRow();

                #endregion

                #region 打印报表
                DataSet set = new DataSet("ds");
                set.Tables.Add(tableTitle);
                set.Tables.Add(tableDetail);
                set.Tables.Add(tableSubDetail);
                set.Tables.Add(tableBottom);

                if(!Directory.Exists(@"C:\Windows\xmldata\")){
                    Directory.CreateDirectory(@"C:\Windows\xmldata\");
                }
                set.WriteXml(@"C:\Windows\xmldata\PrintShopBill.xml", XmlWriteMode.WriteSchema); //保存到本地，为重打
                report.RegisterData(tableTitle, "tableTitle");
                report.RegisterData(tableDetail, "tableDetail");
                report.RegisterData(tableSubDetail, "tableSubDetail");
                report.RegisterData(tableBottom, "tableBottom");


                //设置合计参数
                report.SetParameterValue("Para_TotalNum", Para_TotalNum);
                report.SetParameterValue("Para_TotalAreas", Para_TotalAreas);
                report.SetParameterValue("Para_TotalCount", Para_TotalCount);
                report.SetParameterValue("Para_Sum", Para_Sum);
                report.SetParameterValue("Para_TotalPrintCount", Para_TotalPrintCount);
                report.SetParameterValue("Para_TotalProductCount", Para_TotalProductCount);
                report.Prepare();
                report.Print();
                //FastReport.Export.Html.HTMLExport export = new FastReport.Export.Html.HTMLExport();


                //export.AllowOpenAfter = false;



                //string filePath = Application.StartupPath + "\\currPrint.html";
                //report.Export(export,filePath);


                #endregion

                #region 保存报表到本地
                report1.RegisterData(tableTitle, "tableTitle");
                report1.RegisterData(tableDetail, "tableDetail");
                report1.RegisterData(tableSubDetail, "tableSubDetail");
              
                report1.Prepare();
                string excelPath = Application.StartupPath + "\\报表文件\\" + sbinfo.Shop.shopName;

                if (!Directory.Exists(excelPath))
                {
                    Directory.CreateDirectory(excelPath);
                }
                string repPath = excelPath + "\\" + DateTime.Now.ToString("yyMMddHHmmss") + ".fpx";
                report1.SavePrepared(repPath);
                WCFMINERP.DisjoinProForOutShop.Properties.Settings.Default.LastPrintPath = "0|" + repPath;
                WCFMINERP.DisjoinProForOutShop.Properties.Settings.Default.Save();
                #endregion
            }
            catch (Exception ex)
            {
                WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + ex.Message.ToString());
                WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + ex.StackTrace.ToString());
            }
        }

        /// <summary>
        /// 产品明细表
        /// </summary>
        /// <returns></returns>
        public DataTable CreatePrintDataTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("OrderBagId", typeof(int));
            table.Columns.Add("OrderProductId", typeof(int));
            table.Columns.Add("OrderProductCode", typeof(string));
            table.Columns.Add("BagCode", typeof(string));
            table.Columns.Add("BagName", typeof(string));
            table.Columns.Add("ShopName", typeof(string));
            table.Columns.Add("OrderProductName", typeof(string));
            table.Columns.Add("CtmName", typeof(string));
            table.Columns.Add("ProductName", typeof(string));
            table.Columns.Add("ProductCode", typeof(string));
            table.Columns.Add("ProductNum", typeof(int));
            table.Columns.Add("CreateTime", typeof(DateTime));
            table.Columns.Add("PreFetchTime", typeof(DateTime));
            table.Columns.Add("OutRemark", typeof(string));
            table.Columns.Add("FetchTime", typeof(DateTime));
            table.Columns.Add("FetchRemark", typeof(string));
            table.Columns.Add("CreateUserName", typeof(string));
            table.Columns.Add("Size", typeof(string));
            table.Columns.Add("PhotoNum", typeof(int));


            return table;
        }
        /// <summary>
        /// 商户信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopTop()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ShopId", typeof(int));
            table.Columns.Add("shopName", typeof(string));
            table.Columns.Add("shopKeeper", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("address", typeof(string));

            return table;

        }
        /// <summary>
        /// 为外商信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateOutShopTop()
        {
            DataTable table = new DataTable();
            table.Columns.Add("OutShopId", typeof(int));
            table.Columns.Add("OutShopName", typeof(string));
            table.Columns.Add("Keeper", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("City", typeof(string));
            table.Columns.Add("Addr", typeof(string));
            table.Columns.Add("Code", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            table.Columns.Add("Type", typeof(bool));
            table.Columns.Add("BillID", typeof(string));
            table.Columns.Add("BillIndex", typeof(string));
            return table;

        }
        /// <summary>
        /// 创建title表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillTitle()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ShopName", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("ShopId", typeof(int));
            table.Columns.Add("BillOrderCode", typeof(string));
            table.Columns.Add("shopKeeper", typeof(string));
            table.Columns.Add("QQ", typeof(string));
            table.Columns.Add("BillId", typeof(string));
            table.Columns.Add("CreateTime", typeof(DateTime));
            table.Columns.Add("Balance", typeof(double));
            table.Columns.Add("BillCount", typeof(double));
            table.Columns.Add("CreditLevel", typeof(int));
            table.Columns.Add("Salesman", typeof(string));
            table.Columns.Add("Adress", typeof(string));
            table.Columns.Add("CheckOutType", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            return table;

        }
        /// <summary>
        /// 创建明细产品
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillDetail()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillDetailId", typeof(int));
            table.Columns.Add("OrderInfoCode", typeof(string));
            table.Columns.Add("OrderProductName", typeof(string));
            table.Columns.Add("CtmName", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            table.Columns.Add("OrderBagName", typeof(string));
            return table;
        }
        /// <summary>
        /// 创建明细收费项目表
        /// 
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillSubDetail()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillDetailId", typeof(int));
            table.Columns.Add("DetailName", typeof(string));
            table.Columns.Add("Spec", typeof(string));
            table.Columns.Add("Num", typeof(int));
            table.Columns.Add("UnitPrice", typeof(double));
            table.Columns.Add("Count", typeof(double));
            table.Columns.Add("Area", typeof(double));
            table.Columns.Add("Type", typeof(int));
            table.Columns.Add("DetailRemark", typeof(string));
            return table;
        }
        /// <summary>
        /// 创建发货信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateFahuoTable()
        {
            DataTable table = new DataTable("tableBottom");
            table.Columns.Add("ConsigneeName", typeof(string));
            table.Columns.Add("ConsigneeTelePhone", typeof(string));
            table.Columns.Add("DistributionAddress", typeof(string));
            table.Columns.Add("BusTimetable", typeof(string));//收货单位
            table.Columns.Add("ReMark", typeof(string));
            table.Columns.Add("DistributionMode", typeof(string));
            table.Columns.Add("Fahuodanwei", typeof(string));
            table.Columns.Add("Fahuodianhua", typeof(string));

            return table;
        }

        [DllImport("shell32.dll ")]
        public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);

        public void RePrint()//重新打印前面打印的东东
        {
            //Report report = new Report();
            string fr = WCFMINERP.DisjoinProForOutShop.Properties.Settings.Default.LastPrintPath;
            string type = fr.Split('|')[0];
            string path = fr.Split('|')[1];
            //path=@"D:\Projects\MINERP3.0\MINERP\MINERP.UserLogin\bin\Debug\报表文件\Y演示商户367\2010-7-16 16 04 03.frx";
            if (type.Equals("0"))//分堆
            {
                //report.LoadPrepared(path);
                //if (report.Prepare())
                //    report.ShowPrepared();
                ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder("explorer.exe"),
                                     new StringBuilder(path), new StringBuilder(string.Empty), 1);
            }
  
            
        }

    }
}
